package com.woniuxy.consumer;

import com.rabbitmq.client.Channel;
import com.woniuxy.entity.DTO.FlashSalesDTO;
import com.woniuxy.entity.DTO.QueryTimeSaleGoodsDTO;
import com.woniuxy.entity.FlashSaleProducts;
import com.woniuxy.entity.ShoppingCart;
import com.woniuxy.mapper.FlashSalesMapper;
import com.woniuxy.util.RabbitMQConst;
import com.woniuxy.util.RabbitMQMessageHelper;
import com.woniuxy.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：admin
 * @version ：1.0
 * @date ：Created in 2025/5/16 14:44
 * @description ：限时抢购消费者类
 * @modified_by ：
 */
@Slf4j
@Component
public class TimeSaleConsumer {
    @Resource
    private RedisTemplate<String, Object> redisTemplateInit;

    @Resource
    private FlashSalesMapper flashSalesMapper;

    /**
     * <p>将活动信息预热到 redis 缓存。</p>
     *
     * @param flashSalesDTO 活动信息
     * @param channel       channel
     * @param message       message
     */
    @RabbitListener(queues = RabbitMQConst.TIME_SALE_PREHEAT_QUEUE)
    public void receivePreheatMessage(FlashSalesDTO flashSalesDTO, Channel channel, Message message) {
        RabbitMQMessageHelper.processMessageWithAck(channel, message, msg -> {
            // 检查 redis 中是否已存在该活动信息
            String h = "TIME_SALE_PREHEAT";
            Integer hk = flashSalesDTO.getSaleId();
            Object o = redisTemplateInit.opsForHash().get(h, hk);
            if (o == null) { // 如果不存在，则代表该活动未存入缓存，先将该活动存入缓存
                redisTemplateInit.opsForHash().put(h, hk, flashSalesDTO);
            }
        });
    }

    /**
     * <p>将活动商品信息添加到数据库，并维护商品库存。</p>
     *
     * @param flashSaleProductsList 活动商品信息列表
     * @param channel               channel
     * @param message               message
     */
    @RabbitListener(queues = RabbitMQConst.ADD_TIME_SALE_QUEUE)
    public void receiveAddTimeSale(List<FlashSaleProducts> flashSaleProductsList, Channel channel, Message message) {
        RabbitMQMessageHelper.processMessageWithAck(channel, message, msg -> {
            flashSalesMapper.insertBatchTimeSale(flashSaleProductsList); // 将活动商品添加到数据库
            flashSalesMapper.updateBatchMinusStock(flashSaleProductsList); // 减去活动库存
        });
    }

    /**
     * <p>将抢购购物车信息添加到数据库。</p>
     *
     * @param queryTimeSaleGoodsDTOList 抢购购物车信息列表
     * @param channel                   channel
     * @param message                   message
     */
    @RabbitListener(queues = RabbitMQConst.SAVE_CART_QUEUE)
    public void receiveSaveCart(List<QueryTimeSaleGoodsDTO> queryTimeSaleGoodsDTOList, Channel channel, Message message) {
        RabbitMQMessageHelper.processMessageWithAck(channel, message, msg -> {
            Integer userId = queryTimeSaleGoodsDTOList.get(0).getUserId();
            queryTimeSaleGoodsDTOList.forEach(cart -> cart.setUserId(userId));
            // 第一次添加购物车的商品
            List<QueryTimeSaleGoodsDTO> firstAddCart = queryTimeSaleGoodsDTOList
                    .stream()
                    .filter(timeSaleGoods -> timeSaleGoods.getCartId() == null)
                    .collect(Collectors.toList());
            if (!firstAddCart.isEmpty()) {
                flashSalesMapper.insertShoppingCart(firstAddCart);
            }
            // 非第一次添加购物车的商品
            List<QueryTimeSaleGoodsDTO> notFirstAddCart = queryTimeSaleGoodsDTOList
                    .stream()
                    .filter(timeSaleGoods -> timeSaleGoods.getCartId() != null)
                    .collect(Collectors.toList());
            if (!notFirstAddCart.isEmpty()) {
                flashSalesMapper.updateShoppingCart(notFirstAddCart);
            }
        });
    }
}
